package com.novatialabs.qttt.gwt.client;

import java.util.List;
import java.util.Map;

import com.novatialabs.qttt.gwt.client.Move.State;

public class StandardNotation extends BaseNotation {
  public final static String COLLAPSE_LEFT = "<";
  public final static String COLLAPSE_RIGHT = ">";
  public final static String ENTAGLED = "~";
  public final static String NOT_PLAYED = ",";
  private final static Map<String, State> char2state = State.createSymbol2StateMap(COLLAPSE_LEFT,
      COLLAPSE_RIGHT, ENTAGLED, NOT_PLAYED);
  private final static Map<State, String> state2char = State.createState2SymbolMap(COLLAPSE_LEFT,
      COLLAPSE_RIGHT, ENTAGLED, NOT_PLAYED);

  @Override
  public String printGame(GameModel g) {
    StringBuilder sb = new StringBuilder();
    List<Move> moves = g.getMoves();
    if (moves.size() == 1 && moves.get(0).getState() == Move.State.NOT_PLAYED) {
      return "";
    }
    boolean first = true;
    for (Move m : moves) {
      if (first) {
        first = false;
      } else {
        if (m.getState() != Move.State.NOT_PLAYED) {
          sb.append(getMoveSeperator());
        }
      }
      sb.append(printMove(m));
    }
    return sb.toString();
  }

  @Override
  public String printMove(Move m) {

    return "" + m.getFirstMark() + printStateSymbol(m.getState()) + m.getSecondMark();
  }

  private String printStateSymbol(State state) {

    return state2char.get(state);
  }

  @Override
  public Move parseMove(String text) {
    // blank ?
    if (text == null || text.length() == 0) {
      return Move.BLANK_MOVE;
    }
    if (text.length() != 3 || text.length() < 2) {
      throw new IllegalArgumentException("Move format is 3 characters long");
    }

    int mark1 = Integer.parseInt(text.substring(0, 1));
    int mark2 = Integer.parseInt(text.substring(2, 3));
    State state = parseState(text.substring(1, 2));

    text = text.trim();
    // blank ?
    if (text.length() == 0) {
      return Move.BLANK_MOVE;
    }

    mark1 = Integer.parseInt(text.substring(0, 1));
    mark2 = Integer.parseInt(text.substring(2, 3));
    if (text.length() == 4) {
      state = parseState(text.substring(3, 4));
    }
    if (mark2 != 0 && mark1 > mark2) {
      final int temp = mark1;
      mark1 = mark2;
      mark2 = temp;
    }
    return new Move(mark1, mark2, state);
  }

  private State parseState(String c) {
    State state = char2state.get(c);
    return state;
  }

  @Override
  protected String getMoveSeperator() {
    return ";";
  }
}
